<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="dataForm.userName" placeholder="登录帐号"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.password" type="password" placeholder="密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="comfirmPassword" :class="{ 'is-required': !dataForm.id }">
        <el-input v-model="dataForm.comfirmPassword" type="password" placeholder="确认密码"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
      </el-form-item>
      <!-- <el-form-item label="角色" size="mini" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->
      <el-form-item label="状态" size="mini" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <span v-if="this.show">
      <el-form-item label="供应商编号" prop="artCode">
        <el-input v-model="dataForm.artCode" placeholder="供应商编号"></el-input>
      </el-form-item>
      <el-form-item label="公司名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="公司名称"></el-input>
      </el-form-item>
      <el-form-item label="供应商类型" prop="enterpriseType">
        <el-select v-model="dataForm.enterpriseType" placeholder="供应商类型">
          <el-option label="个体" value=1 ></el-option>
          <el-option label="工厂" value=2 ></el-option>
          <el-option label="公司" value=3 ></el-option>
          <el-option label="集团" value=4 ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="directors">
        <el-input v-model="dataForm.directors" placeholder="联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系人电话" prop="directorMoblie">
        <el-input v-model="dataForm.directorMoblie" placeholder="联系人电话"></el-input>
      </el-form-item>
      <el-row>
        <el-form-item label="所在区域" prop="directorMoblie">
          <el-col>
            <el-select v-model="dataForm.provinceId" placeholder="请选择省" @change="provinceChanged">
              <el-option 
                v-for="item in dataForm.provinceList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.cityId" placeholder="请选择市" @change="provinceChanged1">
              <el-option 
                v-for="item in dataForm.cityList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="dataForm.areaId" placeholder="请选择区">
              <el-option 
                v-for="item in dataForm.areaList"
                :key="item.id"
                :label="item.areaName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          </el-form-item>
        </el-row>
      <el-form-item label="收货地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="收货地址"></el-input>
      </el-form-item>
      <el-form-item label="开户银行" prop="bankName">
        <el-input v-model="dataForm.bankName" placeholder="开户银行"></el-input>
      </el-form-item>
      <el-form-item label="收款账户名" prop="bankUsername">
        <el-input v-model="dataForm.bankUsername" placeholder="收款账户名"></el-input>
      </el-form-item>
      <el-form-item label="收款账户" prop="bankNo">
        <el-input v-model="dataForm.bankNo" placeholder="收款账户"></el-input>
      </el-form-item>
      <el-form-item label="结算方式" prop="settlement">
        <el-select v-model="dataForm.settlement" placeholder="结算方式">
          <el-option label="现结" value=1 ></el-option>
          <el-option label="周结" value=2 ></el-option>
          <el-option label="月结" value=3 ></el-option>
          <el-option label="季结" value=4 ></el-option>
          <el-option label="年结" value=5 ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="微信号" prop="wxNo">
        <el-input v-model="dataForm.wxNo" placeholder="微信号"></el-input>
      </el-form-item>
      <el-form-item label="传真" prop="fax">
        <el-input v-model="dataForm.fax" placeholder="传真"></el-input>
      </el-form-item>
      <el-form-item label="营业资质图片" prop="operatingQualifiedImgurl">
      <!-- <el-input v-model="dataForm.imgName" placeholder="图片名称"></el-input> -->
      <el-upload
      :action="this.$http.adornUrl(`/business/goods/uploadImg?token=${this.$cookie.get('token')}`)"
      :limit="1"
      list-type="picture-card"
      :file-list="dataForm.operatingQualifiedImgurl"
      :on-preview="handlePreview"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :on-exceed="onExceed">
      <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="dialogVisible" :append-to-body='true'>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="dataForm.remarks" placeholder="备注"></el-input>
      </el-form-item>
      </span>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validatePassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('密码不能为空'))
        } else {
          callback()
        }
      }
      var validateComfirmPassword = (rule, value, callback) => {
        if (!this.dataForm.id && !/\S/.test(value)) {
          callback(new Error('确认密码不能为空'))
        } else if (this.dataForm.password !== value) {
          callback(new Error('确认密码与密码输入不一致'))
        } else {
          callback()
        }
      }
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        dialogImageUrl: '',
        dialogVisible: false,
        roleList: [],
        roleId: '',
        show: false,
        dataForm: {
          id: 0,
          userName: '',
          password: '',
          comfirmPassword: '',
          salt: '',
          email: '',
          mobile: '',
          roleIdList: [],
          status: 1,
          artCode: '',
          name: '',
          enterpriseType: '',
          directors: '',
          directorMoblie: '',
          address: '',
          bankName: '',
          bankUsername: '',
          bankNo: '',
          settlement: '',
          wxNo: '',
          fax: '',
          remarks: '',
          operatingQualifiedImgurl: [],
          provinceId: '',
          province: '',
          provinceList: [],
          cityId: '',
          city: '',
          cityList: [],
          areaId: '',
          area: '',
          areaList: []
        },
        dataRule: {
          userName: [
            { required: true, message: '用户名不能为空', trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          comfirmPassword: [
            { validator: validateComfirmPassword, trigger: 'blur' }
          ],
          email: [
            { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ]
        }
      }
    },
    watch: {
      'dataForm.roleIdList': function (val) {
        if (val === 6) {
          this.show = true
        } else {
          let c = false
          for (var i = 0; i < this.dataForm.roleIdList.length; i++) {
            if (this.dataForm.roleIdList[i] === 6) {
              c = true
            }
          }
          this.show = c
        }
      }
    },
    methods: {
      // 图片预览
      handlePreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 文件上传成功的钩子函数
      handleSuccess (res, file, fileList) {
        this.$message({
          type: 'info',
          message: '图片上传成功',
          duration: 6000
        })
        if (res.code === 0) {
          this.dataForm.operatingQualifiedImgurl.push({name: 'tu', url: 'https://image.yilianbaihui.cn/consumer/goods/' + res.data})
        }
        // console.log(this.dataForm.img)
      },
      // 删除文件之前的钩子函数
      handleRemove (file, fileList) {
        // debugger
        for (var i = 0; i < this.dataForm.operatingQualifiedImgurl.length; i++) {
          var picc = this.dataForm.operatingQualifiedImgurl[i]
          if (picc.url === file.url) {
            this.dataForm.operatingQualifiedImgurl.splice(i, 1)
          }
        }
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        })
      },
      roleIdClick (roleId) {
        debugger
        this.roleId = roleId
      },
      // 上传的文件个数超出设定时触发的函数
      onExceed (files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传1个图片',
          duration: 6000
        })
      },
      init (id) {
        this.dataForm.artCode = ''
        this.dataForm.name = ''
        this.dataForm.enterpriseType = ''
        this.dataForm.directors = ''
        this.dataForm.directorMoblie = ''
        this.dataForm.address = ''
        this.dataForm.bankName = ''
        this.dataForm.bankUsername = ''
        this.dataForm.bankNo = ''
        this.dataForm.settlement = ''
        this.dataForm.wxNo = ''
        this.dataForm.fax = ''
        this.dataForm.remarks = ''
        this.dataForm.provinceId = ''
        this.dataForm.province = ''
        this.dataForm.provinceList = []
        this.dataForm.cityId = ''
        this.dataForm.city = ''
        this.dataForm.cityList = []
        this.dataForm.areaId = ''
        this.dataForm.area = ''
        this.dataForm.areaList = []
        this.dataForm.operatingQualifiedImgurl = []
        this.show = false
        this.dataForm.id = id || 0
        this.$http({
          url: this.$http.adornUrl('/member/area/queryProvinceList'),
          method: 'post'
        }).then(({data}) => {
          this.dataForm.provinceList = data.data
        })
        this.$http({
          url: this.$http.adornUrl('/sys/role/select'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          this.roleList = data && data.code === 0 ? data.list : []
        }).then(() => {
          this.visible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].resetFields()
          })
        }).then(() => {
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.userName = data.user.username
                this.dataForm.salt = data.user.salt
                this.dataForm.email = data.user.email
                this.dataForm.mobile = data.user.mobile
                this.dataForm.roleIdList = data.user.roleIdList
                for (var i = 0; i < this.dataForm.roleIdList.length; i++) {
                  if (this.dataForm.roleIdList[i] === 6) {
                    this.show = true
                  }
                }
                this.dataForm.status = data.user.status
                this.dataForm.artCode = data.user.artCode
                this.dataForm.name = data.user.name
                this.dataForm.enterpriseType = data.user.enterpriseType
                this.dataForm.directors = data.user.directors
                this.dataForm.directorMoblie = data.user.directorMoblie
                this.dataForm.address = data.user.address
                this.dataForm.bankName = data.user.bankName
                this.dataForm.bankUsername = data.user.bankUsername
                this.dataForm.bankNo = data.user.bankNo
                this.dataForm.settlement = data.user.settlement
                this.dataForm.wxNo = data.user.wxNo
                this.dataForm.fax = data.user.fax
                this.dataForm.remarks = data.user.remarks
                if (data.user.operatingQualifiedImgurl !== '' && data.user.operatingQualifiedImgurl != null) {
                  this.dataForm.operatingQualifiedImgurl.push({name: 'tu', url: data.user.operatingQualifiedImgurl})
                }
                this.dataForm.provinceId = data.user.provinceId
                this.dataForm.province = data.user.area
                // this.dataForm.provinceList.push({id: data.data.provinceId, name: data.data.province})
                this.dataForm.cityId = data.user.cityId
                this.dataForm.city = data.user.city
                // this.dataForm.cityList.push({id: data.data.cityId, name: data.data.city})
                this.dataForm.areaId = data.user.areaId
                this.dataForm.area = data.user.province
                if (this.dataForm.cityId != null && this.dataForm.city != null) {
                  this.dataForm.cityList = [{id: this.dataForm.cityId, areaName: this.dataForm.city}]
                }
                if (this.dataForm.areaId != null && this.dataForm.area != null) {
                  this.dataForm.areaList = [{id: this.dataForm.areaId, areaName: this.dataForm.area}]
                }
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        let img = []
        debugger
        if (this.dataForm.operatingQualifiedImgurl.length > 0 && this.dataForm.id && this.dataForm.id !== 0) {
          img = this.dataForm.operatingQualifiedImgurl[0].url
        } else if (this.dataForm.operatingQualifiedImgurl.length > 0 && !this.dataForm.id) {
          img.push(this.dataForm.operatingQualifiedImgurl[0].url)
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.id || undefined,
                'username': this.dataForm.userName,
                'password': this.dataForm.password,
                'salt': this.dataForm.salt,
                'email': this.dataForm.email,
                'mobile': this.dataForm.mobile,
                'status': this.dataForm.status,
                'artCode': this.dataForm.artCode,
                'name': this.dataForm.name,
                'enterpriseType': this.dataForm.enterpriseType,
                'directors': this.dataForm.directors,
                'directorMoblie': this.dataForm.directorMoblie,
                'address': this.dataForm.address,
                'bankName': this.dataForm.bankName,
                'bankUsername': this.dataForm.bankUsername,
                'bankNo': this.dataForm.bankNo,
                'settlement': this.dataForm.settlement,
                'wxNo': this.dataForm.wxNo,
                'fax': this.dataForm.fax,
                'remarks': this.dataForm.remarks,
                'operatingQualifiedImgurl': img,
                'provinceId': this.dataForm.provinceId,
                'cityId': this.dataForm.cityId,
                'areaId': this.dataForm.areaId
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      provinceChanged (id) {
        this.$http({
          url: this.$http.adornUrl('/member/area/querySubordinateList'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({data}) => {
          this.dataForm.city = ''
          this.dataForm.area = ''
          this.dataForm.cityId = ''
          this.dataForm.areaId = ''
          this.dataForm.cityList = data.data
        })
      },
      provinceChanged1 (id) {
        this.$http({
          url: this.$http.adornUrl('/member/area/querySubordinateList'),
          method: 'post',
          data: this.$http.adornData(id, false)
        }).then(({data}) => {
          this.dataForm.area = ''
          this.dataForm.areaId = ''
          this.dataForm.areaList = data.data
        })
      }
    }
  }
</script>
